<template lang="pug">
.aliUpload
  .ali-upload
    slot
    input.ali-upload-input(type="file" ref="ossUpload" :multiple="multiple" :accept="accept" @change="doUpload")
</template>

<script>
let OSS = require("ali-oss")
let client = null
import md5 from 'js-md5'
import uuid from 'uuid/v4'
import { getStsInformation, postSaveFile } from 'api'
export default {
	name: 'aliUpload',
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: ''
    },
    fileAgain: {
      type: Object,
      default: null
    }
  },
  watch: {
    async fileAgain (item) {
      let _this = this
      if (item) {
        const progress = async function (p, cpt, res) {
          item.progress = Math.round(p * 100)
          if (cpt) {
            item.name = cpt.name
            item.uploadId = cpt.uploadId
          }
          _this.$emit("getAgainProgress", item)
        }
        client.multipartUpload(item.tmpName, item.file, {
          progress,
          headers: {
            'x-oss-object-acl': 'public-read-write'
          },
          meta: {
            year: 2022,
            people: "test",
          }
        }).then(async res => {
          let fileUrl = res.res.requestUrls[0].split("?")[0]
          let head = client.head(item.tmpName)
          let info = {}
          info.name = res.name
          info.size = item.size
          info.fileSrc = fileUrl
          info.fileName = item.file.name
          info.uid = item.uid
          let query = {
            fileName: item.file.name,
            fileSize: item.size,
            fileUrl: fileUrl
          }
          const { ResultSet } = await _this.$axios.post(postSaveFile, { fileIdList: [{ ...query }] })
          info.fileUrl = ResultSet.userData.fileIdList[0].fileUrl
          info.fileId = ResultSet.userData.fileIdList[0].fileId
          _this.$emit("getFileInfo", [info])
        }).catch(err => {
          console.log(err)
          item.isSuccess = 2 // 2为失败
          _this.$emit("getAgainProgress", item)
        })
      }
    }
  },
	data () {
		return {
			fileName:'',
			videoUrl: '',
			size:''
		}
	},
	methods: {
    async doUpload(event) {
      await this.init()
      let file = Object.values(event.target.files)
      let tempFileList = await Promise.all(file.map(item => {
        let tmpArr = item.name.split(".")
        let tmpName = md5(Date.now() + tmpArr[0])
        let newDate = new Date().format('yyyy-MM-dd')
        tmpName = 'Material/' + newDate + '/' + tmpName + "." + tmpArr[1]
        let reader = new FileReader()
        reader.readAsDataURL(item)
        let row = {
          uid: uuid(),
          size: item.size,
          progress: 0,
          isSuccess: 1,
          tmpName: tmpName,
          file: item,
          fileName: item.name,
        }
        reader.onload = function () {
          row.fileSrc = reader.result
        }
        return row
      }))
      await this.multipartUpload(tempFileList)
      if (this.$refs.ossUpload && this.$refs.ossUpload.value) this.$refs.ossUpload.value =''
    },
    async multipartUpload (fileList) {
      let _this = this
      let list = await Promise.all(fileList.map(item => {
        const progress = async function (p, cpt, res) {
          item.progress = Math.round(p * 100)
          if (cpt) {
            item.name = cpt.name
            item.uploadId = cpt.uploadId
          }
          _this.$emit("getProgress", fileList)
        }
        return client.multipartUpload(item.tmpName, item.file, {
          progress,
          headers: {
            'x-oss-object-acl': 'public-read-write'
          },
          meta: {
            year: 2022,
            people: "test",
          }
        }).then(async res => {
          let fileUrl = res.res.requestUrls[0].split("?")[0]
          let head = client.head(item.tmpName)
          let info = {}
          info.name = res.name
          info.size = item.size
          info.uid = item.uid
          info.fileSrc = fileUrl
          info.fileName = item.file.name
          let query = {
            fileName: item.file.name,
            fileSize: item.size,
            fileUrl: fileUrl
          }
          const { ResultSet } = await _this.$axios.post(postSaveFile, { axiosType: 'upload', fileList: [{ ...query }] })
          info.fileUrl = ResultSet.userData.fileIdList[0].fileUrl
          info.fileId = ResultSet.userData.fileIdList[0].fileId
          return info
        }).catch(err => {
          console.log(err)
          item.isSuccess = 2 // 2为失败
          _this.$emit("getProgress", fileList)
        })
      }))
      _this.$emit("getFileInfo", list)
    },
    async init () {
      try {
        const { ResultSet } = await this.$axios.post(getStsInformation)
        let _this = this
        client = new OSS({
          region: ResultSet.userData.regionId,
          secure: false, // secure: 配合region使用，如果指定了secure为true，则使用HTTPS访问
          accessKeyId: ResultSet.userData.accessKeyId,
          accessKeySecret: ResultSet.userData.accessKeySecret,
          stsToken: ResultSet.userData.securityToken,
          bucket: ResultSet.userData.bucketName,
          endpoint: ResultSet.userData.endPointUrl,
          secure: true,
          refreshSTSToken: async () => {
            // 向您搭建的STS服务获取临时访问凭证。
            const { ResultSet } = await _this.$axios.post(getStsToken)
            return {
              accessKeyId: ResultSet.userData.accessKeyId,
              accessKeySecret: ResultSet.userData.accessKeySecret,
              stsToken: ResultSet.userData.securityToken
            }
          },
        })
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  mounted () {
    // this.init()
  },
}
</script>

<style lang="scss" scoped>
.ali-upload {
  position: relative;
}
.ali-upload-input {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
  cursor: pointer;
}
</style>